package cn.xm.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.xm.utils.JDBCUtils;
import cn.xm.vo.User;

public class UserDaoImpl implements UserDao {
	/**
	 * 登录方法 的实现
	 */
	public User login(User user) {
		//用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		//编写查找的sql语句
		String sql = "select * from user where username = ? and password = ?";
		//定义一个用户
		User existUser;
		try {
			//通过queryRunner把信息存放到用户里面
			existUser = queryRunner.query(sql, new BeanHandler<User>(User.class), user.getUsername(),user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("用户登录失败!");
		}
		//返回用户
		return existUser;
	}
	/**
	 * 注册保存用户信息方法的实现
	 */
	@Override
	public int save(User user) {
		//添加用户的sql
		String sql="insert into user value(null,?,?,?,?,?,?,?,?,?,?) ";
		//用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			//用queryRunner保存用户信息
			result = queryRunner.update(sql, 
								user.getUsername(),
								user.getPassword(),
								user.getType(),
								user.getEmail(),
								user.getAuditFlag(),
								user.getCreateDate(),
								user.getCreateBy(),
								user.getUpdateDate(),
								user.getUpdateBy(),
								user.getDeleteFlag());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 通过用户名得到用户的集合，
	 */
	@Override
	public List<User> getUserListByUserName(String userName) {
		//用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		//通过用户名查找用户信息的sql语句.
		String sql="select * from user where username=? ";
		//创建一个用户的集合ListUser
		List<User> ListUser = new ArrayList<User>();
		try {
			//通过queryRunner的query方法将用户的集合信息放到ListUser里！
			 ListUser = queryRunner.query(sql, new BeanListHandler<User>(User.class), userName);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//返回用户的集合
		return ListUser;
	}

}
